//
//  FProtocol.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/29.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import MJRefresh
import TZImagePickerController

typealias ShowImageClosure = (([UIImage]) -> Void)?

//MARK: - 圆角协议
protocol CircleView {
    func setCircle(rect: CGRect, cornerRadius: CGFloat)
}

extension CircleView where Self: UIView {
    func setCircle(rect: CGRect,cornerRadius: CGFloat ) {
        let maskPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
        let maskLayer = CAShapeLayer()
        maskLayer.frame = rect
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
}

/// View底部阴影
protocol BottomShadow {
    
    /// 设置带有圆角的阴影或者没有圆角的阴影（可以设置单边阴影和双边阴影。想要四周溢出阴影请用系统原生的）
    ///
    /// - Parameters:
    ///   - view: 需要添加阴影或者圆角的视图
    ///   - opacity: 阴影的透明度
    ///   - size: 阴影的偏移量(width:左右, height: 上下)偏移量至少大于1才有效果
    ///   - color: 阴影颜色
    ///   - shadowCornerradius: 阴影的圆角
    ///   - viewCornerradius: 视图的圆角
    func setShadow(view: UIView, opacity: CGFloat, size: CGSize, color: UIColor, cornerradius: CGFloat)
}

extension BottomShadow {
    func setShadow(view: UIView, opacity: CGFloat, size: CGSize, color: UIColor, cornerradius: CGFloat) {
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.05) {
            DispatchQueue.main.async {
                view.layer.cornerRadius = cornerradius
                view.layer.masksToBounds = false
                view.layer.shadowOpacity = Float(opacity)
                view.layer.shadowOffset = size
                view.layer.shadowColor = color.cgColor
                let path = UIBezierPath(roundedRect: view.bounds.insetBy(dx: 1, dy: 1), cornerRadius: cornerradius)
                view.layer.shadowPath = path.cgPath
            }
        }
    }
}

// MARK: - 刷新
protocol RefreshH: NSObjectProtocol {
    func refreshHeader(completionHandler: @escaping () -> Void)
    func refreshFooter(completionHandler: @escaping () -> Void)
}

extension RefreshH where Self: UITableView {
    func refreshHeader(completionHandler: @escaping () -> Void) {
        self.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            completionHandler()
            self.mj_header.endRefreshing()
        })
    }
    
    func refreshFooter(completionHandler: @escaping () -> Void) {
        self.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            completionHandler()
            self.mj_footer.endRefreshing()
        })
    }
}

// MARK: - 获取一个纯色图片
protocol ImageFactory {
    func createImage(color: UIColor, height: CGFloat) -> UIImage?
}

extension ImageFactory {
    func createImage(color: UIColor, height: CGFloat) -> UIImage? {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image ?? nil
    }
}

// MARK: - 获取随机数
protocol GetRandomNumber {
    func getRandomNumber(from: NSInteger, to: NSInteger) -> CGFloat
}

extension GetRandomNumber {
    func getRandomNumber(from: NSInteger, to: NSInteger) -> CGFloat {
        //assert(to < from, "to 不能小于 from")
        let b = abs(to - from) + 1
        let a = arc4random() % UInt32(b)
        return CGFloat(NSInteger(a) + from)
        
    }
}

// MARK: - 设置指定位置圆角
/// 设置指定位置圆角
///
/// - Parameters:
///   - aView: 需要设置的View
///   - aCorners: 设置的方向
///   - aSize: 圆角的角度
protocol AddCornerUIRectCorner {
    func addCornerWithView(aView : UIView, aCorners : UIRectCorner, aSize : CGSize) ->Void
}

extension AddCornerUIRectCorner {
    func addCornerWithView(aView : UIView, aCorners : UIRectCorner, aSize : CGSize) ->Void
    {
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.05) {
            DispatchQueue.main.async {
                // 根据矩形画带圆角的曲线
                let maskPath = UIBezierPath.init(roundedRect: aView.bounds, byRoundingCorners: aCorners, cornerRadii: aSize)
                let maskLayer = CAShapeLayer()
                maskLayer.frame = aView.bounds
                maskLayer.path = maskPath.cgPath
                aView.layer.mask = maskLayer
            }
        }
    }
}

//MARK: - 获取路径
protocol GetMainPath {
    func getDataWithPath(fileName: String) -> String
}

extension GetMainPath {
    func getDataWithPath(fileName: String) -> String {
        let filePath: String = NSHomeDirectory() + "/Documents/" + fileName
        return filePath
    }
}

// MARK: - 假数据
protocol FalseData {
    func falseData() -> [ConsultaionHomeListModel]
    func videoFalseData() -> [VideoModel]
    func commodityFalseData() -> [CommodityModel]
}

extension FalseData {
    func falseData() -> [ConsultaionHomeListModel] {
        let dataList = ["camera.plist", "wch.plist", "xhc.plist", "qkl.plist", "oppo.plist", "ipx.plist", "djt.plist"]
        var model: [ConsultaionHomeListModel] = []
        for plist in dataList {
            let path = Bundle.main.path(forResource: plist, ofType: nil)
            let dic = NSDictionary(contentsOfFile: path!) as? [String: Any]
            guard let dataDic = dic else { return [] }
            let tempModel = ConsultaionHomeListModel(dataDic)
            model.append(tempModel)
        }
        return model
    }
    
    func videoFalseData() -> [VideoModel] {
        let dataList = ["use1.plist", "use2.plist", "use3.plist", "use4.plist"]
        var model: [VideoModel] = []
        for plist in dataList {
            let path = Bundle.main.path(forResource: plist, ofType: nil)
            let dic = NSDictionary(contentsOfFile: path!) as? [String: Any]
            guard let dataDic = dic else { return [] }
            let tempModel = VideoModel(dataDic)
            model.append(tempModel)
        }
        return model
    }
    
    func commodityFalseData() -> [CommodityModel] {
        let dataList = ["mask.plist", "translate.plist", "coatHanger.plist", "AR.plist", "BodyFat.plist"]
        var models: [CommodityModel] = []
        for plist in dataList {
            let path = Bundle.main.path(forResource: plist, ofType: nil)
            let dic = NSDictionary(contentsOfFile: path!) as? [String: Any]
            guard let dataDic = dic else { return [] }
            let tempModel = CommodityModel(dataDic)
            models.append(tempModel)
        }
        return models
    }
}

// MARK: - 延时执行
protocol DelayExecution {
    func delayExecution(time: TimeInterval, closure: @escaping () -> Void)
}

extension DelayExecution {
    func delayExecution(time: TimeInterval, closure: @escaping () -> Void) {
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + time) {
            DispatchQueue.main.async {
                closure()
            }
        }
    }
}

// MARK: - 相机and相册权限
protocol CameraAndPhotoPermissions {
    
}

extension CameraAndPhotoPermissions {
    func cameraPermissions(authorizedClosuer: @escaping () -> Void, deniedClosuer: @escaping () -> Void) {
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        
        // .notDetermined .authorized .restricted .denied
        if authStatus == .notDetermined {
            // 第一次触发授权 alert
            AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
                self.cameraPermissions(authorizedClosuer: authorizedClosuer, deniedClosuer: deniedClosuer)
            })
        } else if authStatus == .authorized {
            authorizedClosuer()
        } else {
            deniedClosuer()
        }
    }
    
    func photoAlbumPermissions(authorizedClosuer: @escaping () -> Void, deniedClosuer: @escaping () -> Void) {
        let authStatus = PHPhotoLibrary.authorizationStatus()
        
        // .notDetermined .authorized .restricted .denied
        if authStatus == .notDetermined {
            // 第一次触发授权 alert
            PHPhotoLibrary.requestAuthorization { (status:PHAuthorizationStatus) -> Void in
                self.photoAlbumPermissions(authorizedClosuer: authorizedClosuer, deniedClosuer: deniedClosuer)
            }
        } else if authStatus == .authorized {
            authorizedClosuer()
        } else {
            deniedClosuer()
        }
    }
}

// MARK: - 自定义View的一些基础布局
protocol CustomView {
    var mainView: UIView {get set}
    var isBottomAnimation: Bool {get set}
    func setBasicDataWith(mainViewRect: CGRect)
    func hide()
}

extension CustomView where Self: UIView {
    func setBasicDataWith(mainViewRect: CGRect) {
        
        let window = UIApplication.shared.keyWindow
        self.frame = window!.bounds
        self.alpha = 0.3
        self.backgroundColor = ONColor.maskBGColor
        window?.addSubview(self)
        UIView.animate(withDuration: TimeInterval(anTIME)) {
            self.alpha = 1
        }
        mainView.backgroundColor = UIColor.white
        self.addSubview(mainView)
        if isBottomAnimation {
            mainView.frame = mainViewRect.offsetBy(dx: 0, dy: mainViewRect.height)
            UIView.animate(withDuration: anTIME, animations: {
                self.mainView.frame = mainViewRect
            })
        } else {
            mainView.frame = mainViewRect
            mainView.centerY = self.height / 2
        }
    }
    
    func hide() {
        UIView.animate(withDuration: TimeInterval(anTIME), animations: {
            if self.isBottomAnimation {
                self.mainView.y = ScreenHeight
            }
            
            self.alpha = 0.3
        }) { (make) in
            self.removeFromSuperview()
        }
    }
}

// MARK: - 用相机拍照
protocol ShowCameraVC: CameraAndPhotoPermissions, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 先调用函数 然后用UIImagePickerControllerDelegate获取数据
    func showCamera()
}

extension ShowCameraVC where Self : UIViewController {
    func showCamera() {
        cameraPermissions(authorizedClosuer: {
            let sourceType: UIImagePickerControllerSourceType = .camera
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                let imagePickerController = self.setImagePickerVC()
                imagePickerController.sourceType = sourceType
                imagePickerController.modalPresentationStyle = .currentContext
                self.present(imagePickerController, animated: true, completion: nil)
            }
        }) {
            DispatchQueue.main.async {
                CustomShowAlertView().show(title: "相机权限未开启", tapClosure: {
                    let url = URL(string: UIApplicationOpenSettingsURLString)
                    if let appUrl = url {
                        if UIApplication.shared.canOpenURL(appUrl) {
                            UIApplication.shared.openURL(appUrl)
                        }
                    }
                })
            }
        }
    }
    
    private func setImagePickerVC() -> UIImagePickerController {
        let imagePickerVc = UIImagePickerController()
        imagePickerVc.delegate = self
        imagePickerVc.navigationBar.barTintColor = self.navigationController?.navigationBar.barTintColor
        imagePickerVc.navigationBar.tintColor = self.navigationController?.navigationBar.tintColor
        return imagePickerVc
    }
}

// MARK: - 相册调用
protocol ShowPhotoLibrary: TZImagePickerControllerDelegate, CameraAndPhotoPermissions {
    
    func showPhotoLibrary(count: NSInteger, isSelectVideo: Bool, isCorp: Bool)
}

extension ShowPhotoLibrary where Self: UIViewController {
    
    func showPhotoLibrary(count: NSInteger, isSelectVideo: Bool, isCorp: Bool) {
        photoAlbumPermissions(authorizedClosuer: {
            let imagePickerVc = TZImagePickerController(maxImagesCount: count, delegate: self)
            imagePickerVc?.allowPickingOriginalPhoto = false
            imagePickerVc?.allowPickingVideo = isSelectVideo
            imagePickerVc?.allowPickingGif = false
            imagePickerVc?.allowCrop = isCorp
            imagePickerVc?.didFinishPickingPhotosHandle = {(photos, assets, isSelectOriginalPhoto) in
                
            }
            self.present(imagePickerVc!, animated: true, completion: nil)
        }) {
            DispatchQueue.main.async {
                CustomShowAlertView().show(title: "相册权限未开启", tapClosure: {
                    let url = URL(string: UIApplicationOpenSettingsURLString)
                    if let appUrl = url {
                        if UIApplication.shared.canOpenURL(appUrl) {
                            UIApplication.shared.openURL(appUrl)
                        }
                    }
                })
            }
        }
    }
}
